package com.zhengtoon.mctoon.conv.utils;

import com.bjtoon.framework.sdk.storage.scloud.CloudEntity;
import com.bjtoon.framework.sdk.storage.scloud.PublicScloudStorageService;
import com.bjtoon.framework.sdk.storage.scloud.ScloudStorageService;
import com.bjtoon.framework.utils.http.HttpUtils;
import com.qitoon.framework.core.exception.BusinessException;
import com.systoon.scloud.master.lightsdk.request.RequestUploadResult;
import com.zhengtoon.mctoon.conv.dto.param.UploadInputParam;
import com.zhengtoon.mctoon.conv.exception.ConvPhotoExceptionCode;

import okhttp3.Response;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * 云上传内部工具
 *
 * @author 144637
 */
public class CloudAppUtils {
    private static Logger logger = LoggerFactory.getLogger(CloudAppUtils.class);

    public static final String PREFIX = "scloud";
    //专题图片大小限制 单位:kB
    public static final String SUBJECT_FILE_SIZE_LIMIT = SysConfig.getPropertyValue("config.subject_file_size_limit");

//    public static final String SUBJECT_FILE_SIZE_LIMIT = "5";

    // 1KB=1024 byte
    public static final Integer KILO_BYTE_UNIT = 1024;

    /**
     * 下载文件
     *
     * @param prefix
     * @param url
     * @return
     * @author 137127
     */
    public static File downloadPublicUrl(String prefix, String url) {

        String suffix = getSuffix(url);
        if (null == suffix) {
            return null;
        }
        try {
            File file = File.createTempFile(prefix, suffix);
            Response syncGet = HttpUtils.syncGet(url);
            byte[] data = syncGet.body().bytes();
            FileUtils.writeByteArrayToFile(file, data);
            return file;
        } catch (IOException e) {
            logger.error("下载文件失败，" + e.getMessage(), e);
            throw new BusinessException(ConvPhotoExceptionCode.DOWNLOAD_FILE_FAIL);
        }
    }

    private static String getSuffix(String url) {
        int lastIndexOf = url.lastIndexOf(".");
        if (lastIndexOf > -1) {
            return url.substring(lastIndexOf);
        }
        return null;
    }


    /**
     * 获取公有云路径  144637
     *
     * @param inputParam
     * @return
     */
    public static String getPublicUrl(UploadInputParam inputParam) {

        RequestUploadResult result = new PublicScloudStorageService().uploadFile(getUploadParam(inputParam)); // 公有
        return result.getPubUrl();
    }

    /**
     * 获取公有云路径 专题  144637
     *
     * @param inputParam 云上传入参
     * @return String
     */
    public static String getPublicUrlOfSubject(UploadInputParam inputParam) {
        CloudEntity cloudEntity = getUploadParam(inputParam);
        if (fileOutOfSize(cloudEntity.getFileContent())) {
            throw new BusinessException(ConvPhotoExceptionCode.SUBJECT_FILE_OUT_OF_SIZE);
        }

        RequestUploadResult result = new PublicScloudStorageService().uploadFile(cloudEntity);

        return result.getPubUrl();
    }

    /**
     * 判断文件是否超过限制
     *
     * @param fileContent 文件byte数组
     * @return boolean
     * @author 144637
     */
    private static boolean fileOutOfSize(byte[] fileContent) {
        Integer fileSizeLimit = Integer.valueOf(SUBJECT_FILE_SIZE_LIMIT);
        return fileContent.length > KILO_BYTE_UNIT * fileSizeLimit;
    }

    /**
     * 下载多个文件（后期需要删除）
     *
     * @param urls
     * @return
     * @author 137127
     */
    public static File[] downloadPublicUrls(String... urls) {
        File[] files = new File[urls.length];
        Integer index = 0;
        for (String url : urls) {
            files[index] = downloadPublicUrl(PREFIX + index, url);
            index++;
        }
        return files;
    }

    /**
     * 获取上传参数   144637
     *
     * @return
     */
    public static CloudEntity getUploadParam(UploadInputParam inputParam) {
        CloudEntity param = new CloudEntity();
        param.setSuffix(inputParam.getFileType());
        byte[] bytes = ScloudStorageService.getByteArrayFromBase64(inputParam.getFileStream());
        param.setFileContent(bytes);
        return param;
    }
}
